package com.pai4j.search.messagequeue.consumer;

import com.pai4j.common.enums.ESMessageTypeEum;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.dto.AbstractESMessageDTO;
import com.pai4j.domain.dto.queue.ArticleEsSyncQueueDTO;
import com.pai4j.domain.vo.response.subjectaccount.ArticleBaseResponseVO;
import com.pai4j.search.service.es.SubjectArticleElasticSearchService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@Lazy(false)
public class SubjectArticleSyncRedisQueueConsumer extends AbstractRedisQueueConsumer<ArticleEsSyncQueueDTO> {

    @Resource
    private SubjectArticleElasticSearchService subjectArticleElasticSearchService;

    public void initBean() {
        new Thread(() -> schedule()).start();
    }

    @Override
    protected ArticleEsSyncQueueDTO convert(String s) {
        return JsonUtil.fromJson(s, ArticleEsSyncQueueDTO.class);
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {
        return MessageQueueEnum.QUEUE_SUBJECT_ARTICLE_SYNC_ES;
    }

    @Override
    protected void receive(ArticleEsSyncQueueDTO dtoMsg) throws Exception {
        ArticleBaseResponseVO article = JsonUtil.fromJson(dtoMsg.getArticleJson(), ArticleBaseResponseVO.class);
        subjectArticleElasticSearchService.sync(buildES(article));
    }

    private AbstractESMessageDTO buildES(ArticleBaseResponseVO a) {
        AbstractESMessageDTO dto = new AbstractESMessageDTO();
        dto.setType(ESMessageTypeEum.SUBJECT_ACCOUNT_ARTICLE.getType());
        dto.setBizId(String.valueOf(a.getId()));
        // 可搜索内容：标题 + 描述 + 正文
        StringBuilder content = new StringBuilder();
        if (StringUtils.isNotBlank(a.getTitle())) content.append(a.getTitle());
        if (StringUtils.isNotBlank(a.getDescription())) {
            if (content.length() > 0) content.append(" ");
            content.append(a.getDescription());
        }
        if (StringUtils.isNotBlank(a.getContent())) {
            if (content.length() > 0) content.append(" ");
            content.append(a.getContent());
        }
        dto.setContent(content.toString());
        dto.setData(JsonUtil.toJsonString(a));
        Date now = new Date();
        dto.setCreateDate(now);
        dto.setUpdateDate(now);
        return dto;
    }

    @Override
    protected void error(ArticleEsSyncQueueDTO data, Exception ex) {
        backToQueue(data);
        log.error("SubjectArticleSyncRedisQueueConsumer error", ex);
    }
}
